package org.sunsys.qa.datasource;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class DataSourceProvider {

	private Logger logger = Logger.getLogger(DataSourceProvider.class.getName());
	private DataSource dataSource = null;
	private static DataSourceProvider dataSourceFactoryMethod = null;
	
	private DataSourceProvider() {
	}
	
	public void init(){
		Context context = null;
		String dataSourceName = "jdbc/qadatabase";
		try { 
			context = new InitialContext();
			System.out.println("Initial context instance is created");
			DataSource dataSource = (DataSource)context.lookup("java:/comp/env/"+dataSourceName);
			/* assign to instance variable */
			this.dataSource = dataSource;
			logger.debug("got instance of DataSource from JNDI");
		}catch(NamingException e1) {
			logger.error("Exception while retriving DataSource object from JNDI, with name:"+dataSourceName);
		}
	}
	
	public DataSource getDataSource() {
		return dataSource;
	}
	
	public synchronized static DataSourceProvider getInstance(){
		if( dataSourceFactoryMethod == null) {
			dataSourceFactoryMethod = new DataSourceProvider();
			/* int */
			dataSourceFactoryMethod.init();
		}
		return dataSourceFactoryMethod;
	}
	
}
